import { store } from "@ice/stark-data";
/**
 * 权限控制组件
 * @param authority 权限集合
 * @param noMatch 无匹配时的渲染内容
 * @param children
 * @returns {*}
 * @constructor
 */
const Authorized = ({ authority, noMatch, children }: any) => {
  if (!authority) return children;

  let isPermission = true;

  const getAuths = (store.get("BTN_AUTH") || []).map(
    (item: any) => item.permission
  ); // 从框架获取按钮权限集合

  if (typeof authority === "string") {
    // 单个权限词条
    if (getAuths.indexOf(authority) === -1) {
      isPermission = false;
    }
  } else if (authority instanceof Array && authority.length > 0) {
    // 多个权限词条
    authority.forEach((item) => {
      if (getAuths.indexOf(item) === -1) {
        isPermission = false;
      }
    });
  }

  return isPermission ? children : noMatch;
};
/**
 * 是否有权限
 * @param authority 权限集合
 * @returns {*}
 * @constructor
 */
const isAuthorized = (authority: any) => {
  if (!authority) return true;

  let isPermission = true;

  const getAuths = (store.get("BTN_AUTH") || []).map(
    (item: any) => item.permission
  ); // 从框架获取按钮权限集合

  if (typeof authority === "string") {
    // 单个权限词条
    if (getAuths.indexOf(authority) === -1) {
      isPermission = false;
    }
  } else if (authority instanceof Array && authority.length > 0) {
    // 多个权限词条
    authority.forEach((item) => {
      if (getAuths.indexOf(item) === -1) {
        isPermission = false;
      }
    });
  }
  return isPermission;
};

export { isAuthorized, Authorized };
